<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 、卡片视图区 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <el-table :data="roleslist" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand" label=">">
                    <template slot-scope="scope">
                        <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id"
                            :class="['bdbottom', i1 == 0 ? 'bdtop' : '', 'vcenter']">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <!-- 通过for循环 嵌套渲染二级权限 -->
                                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                                    v-for="(item2, i2) in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{
                                                item2.authName
                                        }}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 渲染三级权限 -->
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id"
                                            closable @close="removeRightById(scope.row, item3.id)">
                                            {{ item3.authName }}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="角色名称" prop="roleName" width="390"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc" width="380"></el-table-column>
                <el-table-column label="操作" width="380">
                    <template slot-scope="scope">
                        <!-- 修改 编辑 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">
                            编辑</el-button>
                        <el-dialog title="添加用户" :visible.sync="editDialogVisible" width="50%">
                            <!-- 内容主题区域  ref="addFormRef"  用来进行预验证-->
                            <el-form ref="addFormRef" :model="editForm" :rules="addFormRules" label-width="70px">
                                <!-- 添加数据 -->
                                <el-form-item label="角色名称" prop="roleName">
                                    <el-input v-model="editForm.roleName"></el-input>
                                </el-form-item>
                                <el-form-item label="角色描述" prop="roleDesc">
                                    <el-input v-model="editForm.roleDesc"></el-input>
                                </el-form-item>
                            </el-form>
                            <!-- 底部区域 -->
                            <span slot="footer" class="dialog-footer">
                                <el-button @click="editDialogVisible = false">取 消</el-button>
                                <el-button type="primary" @click="addRoles(scope.row.id)">确 定</el-button>
                            </span>
                        </el-dialog>

                        <!-- 删除 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                            @click="removeRolesList(scope.row.id)">删除</el-button>
                        <!-- 分配角色 -->
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配角色</el-button>
                        </el-tooltip>
                        <!-- 分配权限对话框 -->
                        <el-dialog title="分配权限" :visible.sync="rightsDilogVisible" width="50%" @close="setRightDialogClosed">
                            <!-- 树形控件 -->
                                <el-tree :data="rightlist" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
                                <span slot="footer" class="dialog-footer">
                                    <el-button @click="rightsDilogVisible = false">取 消</el-button>
                                    <el-button type="primary" @click="allotRights">确 定</el-button>
                                </span>
                            </el-dialog>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加用户 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%">
            <!-- 内容主题区域  ref="addFormRef"  用来进行预验证-->
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="70px">
                <!-- 添加数据 -->
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 角色列表数据
            roleslist: [],
            // 权限数据列表
            rightlist:[],
            treeProps:{
                label:'authName',
                children:'children'
            },
            // 默认选中节点中ID值
            defKeys:[],
            // 当前即将分配权限的id
            roleId:'',
            // 控制添加角色弹出框的显示与隐藏
            addDialogVisible: false,
            // 控制修改角色弹出框的显示与隐藏
            editDialogVisible: false,
            // 控制分配权限弹出啊框的显示和隐藏
            rightsDilogVisible:false,
            // 添加角色对黄框的数据
            addForm: {
                roleName: '张三李四',
                roleDesc: '',
            },
            // 修改用户信息列表
            editForm: {},
            // 添加表单的验证规则对象
            addFormRules: {
                // 验证用户名是否合法
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                // 验证密码
                roleDesc: [
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],

            },
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        // 获取角色列表数据
        async getRolesList() {
            const { data: res } = await this.$http.get("roles", this.addForm)
            if (res.meta.status !== 200) {
                return this.$message.error("获取角色列表失败");
            }
            this.roleslist = res.data
            // console.log(res);
        },
        // 监听 添加用户对话框关闭的事件,
        addDialogClosed() {
            this.$refs.addFormRef.resetFields()
        },

        // 添加用户时的与验证
        addUser() {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return
                // 可以发起请求
                const { data: res } = await this.$http.post("roles", this.addForm)
                if (res.meta.status !== 200) {
                    this.$message.error("添加用户失败")
                }
                this.$message.success("添加角色成功")
                this.addDialogVisible = false
                this.getRolesList()
            })
        },

        // 根据用户di进行查询
        async showEditDialog(id) {
            // console.log(id);
            const { data: res } = await this.$http.get("roles/" + id)
            //    console.log(res);
            if (res.meta.status !== 200) {
                this.$message.error("查询失败")
            }
            this.editForm = res.data
            this.editDialogVisible = true
        },
        //点击确定按钮时，将修改后的数据添加到数据库中
        addRoles(id) {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return
                // 可以发起请求
                const { data: res } = await this.$http.put("roles/" + id, {
                    roleName: this.editForm.roleName,
                    roleDesc: this.editForm.roleDesc
                })
                // console.log(res);
                if (res.meta.status !== 200) {
                    this.$message.error("更新用户信息失败")
                }
                // 关闭对话框
                this.editDialogVisible = false

                //重新调用获取数据，刷新
                this.getRolesList()

                // 提示添加用户信息成功
                this.$message.success("更新用户信息成功")

            })
        },
        // 删除角色信息
        async removeRolesList(id) {
            const confirResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)

            if (confirResult !== 'confirm') {
                return this.$message.info("已取消删除")
            }
            const { data: res } = await this.$http.delete("roles/" + id)
            // console.log(res);
            if (res.meta.status !== 200) {
                this.$message.error("删除用户信息失败")
            }

            this.$message.success("删除用户信息成功")
            // 刷新数据列表
            this.getRolesList()
        },
        // 删除角色
        async removeRightById(role, rightId) {
            const confirResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)

            if (confirResult !== 'confirm') {
                return this.$message.info("已取消删除")
            }
            // 可以发起请求了
            const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            if (res.meta.status !== 200) {
                return this.$message.error("删除权限失败")
            }
            // this.getRolesList()
            role.children = res.data
            this.$message.success("删除权限成功")
            // 
        },
        // 分配权限
        async showSetRightDialog(role){
            const {data:res} = await this.$http.get("rights/tree")
            this.roleId = role.id
            if(res.meta.status !== 200){
                return this.$message.error("获取权限数据失败")
            }
            this.rightlist = res.data
            console.log(this.rightlist);
            // 获取三级节点的id
            this.getdeafKeys(role,this.defKeys)

            this.rightsDilogVisible = true
        },

        // 通过递归的形式，获取角色下所有三级权限的id 并保存到defKeys数组中
        getdeafKeys(node, arr){
            // 如果当前node 节点不包含children属性，则是三级节点
            if(!node.children){
                return arr.push(node.id)
            }
            node.children.forEach(item=>{
                this.getdeafKeys(item,arr)
            })
        },
        // 监听分配权限对话框的关闭事件
        setRightDialogClosed(){
            this.defKeys = []
        },
        // 点击为角色分配权限
        async allotRights(){
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            console.log(keys);

            const idStr = keys.join(',')

            const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,
            {rids:idStr})
            if(res.meta.status !== 200){
                return this.$message.error("分配权限失败")
            }
            this.$message.success("分配权限成功")
            this.getRolesList()
            this.rightsDilogVisible = false
        }
    }

}
</script>

<style lang="less" scoped>
.bdtop {
    border-top: 1px solid #eee;
}

.bdbottom {
    border-bottom: 1px solid #eee;
}

.el-tag {
    margin: 7px;
}

.vcenter {
    display: flex;
    align-items: center;
}
</style>